import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from exchange_manager import ExchangeManager

from common_symbols import CommonSymbolsManager
from logs import setup_arbitrage_logger, setup_order_logger
import asyncio
import ccxt.pro as ccxt
from typing import List
from decimal import Decimal
from database_manager import DatabaseManager
import time


async def _monitor_exchange(exchange_id: str, exchange, symbols: List[str]):
    """监控单个交易所的价格"""
    func_name = 'watchTickers'
    # func_name = 'watchOrderBookForSymbols'
    index = 20
    if exchange.has[func_name]:
        try:
            while True:
                
                try:
                    print(f"监控 {exchange_id} 交易所的 {symbols[index]} 价格")
                    tickers = await getattr(exchange, func_name)(symbols, params={})
                    print(exchange.iso8601(exchange.milliseconds()), list(tickers.values())[index])

                    # time.sleep(1)

                except Exception as e:
                    print(e)
                    # 发生异常时取消订阅
                    if hasattr(exchange, 'unwatchTickers'):
                        await exchange.unwatchTickers()
                    # stop the loop on exception or leave it commented to retry
                    # raise e
        finally:
            # 确保在函数结束时取消订阅
            if hasattr(exchange, 'unwatchTickers'):
                await exchange.unwatchTickers()
    else:
        print(f"{exchange_id} 不支持 {func_name}")


async def test():
    # 初始化交易所管理器
    exchange_manager = ExchangeManager()

    # 加载所有交易所的市场数据
    # await exchange_manager.load_all_markets()

    # 获取共同交易对
    db_manager = DatabaseManager()
    common_symbols = db_manager.get_common_symbols()

    print(len(common_symbols))

    opt = {
        'enableRateLimit': True,
        'options': {
            'defaultType': 'swap',
        },
    }

    for exchange_id, exchange in exchange_manager.get_all_exchanges():
    #     # print(exchange_id)
    #     # print(exchange.name)
        # exchange_id = 'xt'
        # exchange = exchange_manager.get_exchange(exchange_id)
        # exchange = ccxt.xt(opt)
        # await exchange.loadMarkets()

        await _monitor_exchange(exchange_id, exchange, common_symbols)

    # 关闭交易所连接
    await exchange.close()


asyncio.run(test())
